/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
// eslint-disable-next-line @typescript-eslint/no-use-before-define, no-use-before-define
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { Checkbox, Alert, Row, Col } from 'antd';
import Login from '@/components/Login';
import { encryption } from '@/utils/utils';
import Advertisement from '@/components/Advertisement';
import styles from './Login.less';

const { Password, Mobile, PicCaptcha, Submit } = Login;

@connect(({ loading, setting }) => ({
  submitting: loading.effects['login/login'],
  ...setting,
}))
export default class LoginPage extends PureComponent {
  state = {
    type: 'mobile',
    autoLogin: true,
    encrypting: false,
  };

  onTabChange = type => {
    this.setState({ type });
  };

  handleSubmit = async (err, values) => {
    const { type } = this.state;
    const { dispatch } = this.props;
    const { pass, phone } = values;
    if (!err) {
      this.setState({ encrypting: true });
      const encryptedVal = await encryption({ pass, phone });
      this.setState({ encrypting: false });
      dispatch({
        type: 'login/login',
        payload: {
          ...values,
          type,
          ...encryptedVal,
        },
        then: code => {
          if (code == 1066) {
            this.picnode.onGetPicCaptcha();
          }
        },
      });
    }
  };

  changeAutoLogin = e => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };

  renderMessage = content => (
    <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
  );

  // eslint-disable-next-line react/sort-comp
  onChange = e => {
    const rule = /^1\d{10}$/;
    const { value } = e.target;
    const currentMobile = rule.test(value) ? value : '';
    this.setState({
      currentMobile,
    });
    localStorage.setItem('user-info-phone', currentMobile);
  };

  render() {
    const { submitting, location, options } = this.props;
    const { loginBg, key, logo, name, showAdv, subKey } = options;
    const { type, autoLogin, currentMobile = '', encrypting } = this.state;
    const { mobile } = location.state || {};
    const { phone = '' } = JSON.parse(localStorage.getItem('user-info')) || {};
    const userInfoPhone = localStorage.getItem('user-info-phone');
    const urlp = `?phone=${currentMobile || userInfoPhone || phone}`;
    console.log('urlp', urlp);
    const hideRegister = key == 'post' || key == 'yjy';
    const isKbCity = key === 'yz' && showAdv; // 仅适配快宝新零售平台登录页样式
    const isTongDi = subKey == 'td';
    return (
      <div className={styles.main_content}>
        <Row
          style={{ width: '100%', ...(isKbCity ? { margin: 0, height: 632 } : {}) }}
          type="flex"
          justify={isKbCity ? 'space-between' : 'center'}
          gutter={['48', '48']}
          align="middle"
        >
          <Col
            xs={isKbCity ? 0 : 24}
            sm={isKbCity ? 0 : 24}
            md={isKbCity ? 0 : 24}
            lg={isKbCity ? 0 : 24}
            xl={8}
            style={isKbCity ? { padding: 0, width: 776 } : { width: 500 }}
          >
            <Row type="flex" justify="center">
              <Col style={{ width: isKbCity ? 776 : 500 }}>
                {showAdv ? (
                  <Advertisement
                    platform={isTongDi ? 'tong_di' : 'citysite'}
                    advType={isTongDi ? 1 : 2}
                    position="center"
                    type="web"
                    width="776"
                    height="632"
                    direction="horizontal"
                  />
                ) : (
                  <div
                    className={styles.main_left}
                    style={{
                      backgroundImage: `url(${loginBg.url})`,
                      height: loginBg.height,
                    }}
                  />
                )}
              </Col>
            </Row>
          </Col>
          <Col
            xs={24}
            sm={24}
            md={24}
            lg={isKbCity ? 7 : 24}
            xl={7}
            style={{ ...(isKbCity ? { margin: '0 auto' } : {}) }}
            className={styles.loginposition}
          >
            <div className={styles.main}>
              <div className={styles.main__header_title}>
                <Link to="/">
                  <img alt="logo" className={styles.main__header_title__logo} src={logo} />
                  <span className={styles.main__header_title__title}>{name}</span>
                </Link>
              </div>
              <Login
                defaultActiveKey={type}
                onTabChange={this.onTabChange}
                onSubmit={this.handleSubmit}
              >
                <Mobile name="phone" defaultValue={mobile} onBlur={this.onChange} autoFocus />
                <Password name="pass" />

                <PicCaptcha
                  className="captcha"
                  ref={node => {
                    this.picnode = node;
                  }}
                  name="code"
                  action="/Api/Verify/registerCodeGenerator"
                  captchaUrl={urlp}
                />
                <div>
                  <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
                    自动登录
                  </Checkbox>
                  <Link
                    style={{ float: 'right' }}
                    className={styles.register}
                    to={`/user/forget${urlp}`}
                  >
                    忘记密码
                  </Link>
                </div>
                <Submit loading={encrypting || submitting}>登录</Submit>
                {!hideRegister && (
                  <div className={styles.other}>
                    <Link className={styles.register} to={`/user/register${urlp}`}>
                      注册账户
                    </Link>
                  </div>
                )}
              </Login>
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}
